package com.zbb.order.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zbb.order.feignclient.UserServiceClient;
import com.zbb.order.mapper.*;
import com.zbb.order.model.dto.OrderDetailsDto;
import com.zbb.order.model.po.*;
import com.zbb.order.service.OrderDetailsService;
import com.zbb.order.service.ThreadService;
import com.zbb.order.util.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 订单详情表 服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class OrderDetailsServiceImpl extends ServiceImpl<OrderDetailsMapper, OrderDetails> implements OrderDetailsService {

    @Autowired
    OrderDetailsMapper orderDetailsMapper;
    @Autowired
    LabelRelationMapper labelRelationMapper;

    @Autowired
    LabelMapper labelMapper;

    @Autowired
    PictureMapper pictureMapper;

    @Autowired
    OrderInitiateMapper orderInitiateMapper;

    @Autowired
    UserServiceClient userServiceClient;
    @Autowired
    ThreadService threadService;

    @Override
    public OrderDetailsDto selectDetails(String orderId) {
        OrderDetailsDto orderDetailsDto = orderDetailsMapper.selectDetailById(orderId);
        if (orderDetailsDto != null) {
            //根据用户id获取用户信息
            User user = userServiceClient.querytUser(orderDetailsDto.getUserCode());
            //根据订单详情id获取标签
            QueryWrapper<LabelRelation> wrapperLabel = new QueryWrapper<>();
            wrapperLabel.eq("details_id", orderDetailsDto.getId());
            List<LabelRelation> labelRelations = labelRelationMapper.selectList(wrapperLabel);
            List<Label> labels = new ArrayList<>();
            for (LabelRelation labelNos : labelRelations) {
                Label label = labelMapper.selectById(labelNos.getLabelId());
                labels.add(label);
            }
            //根据订单详情id查询图片
            QueryWrapper<Picture> wrapperPicture = new QueryWrapper<>();
            wrapperPicture.eq("order_detail_id", orderDetailsDto.getId());
            List<Picture> pictures = pictureMapper.selectList(wrapperPicture);

            orderDetailsDto.setLabels(labels);
            orderDetailsDto.setPictures(pictures);
            orderDetailsDto.setUser(user);
        }
        threadService.updateOrderViewCount(orderInitiateMapper,orderId);
        return orderDetailsDto;
    }


}
